package pers.zw.study.mysql.utils;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.Properties;
import java.util.logging.Logger;

public class JdbcPool implements DataSource {

    private static LinkedList<Connection> listConnections = new LinkedList<>();

    static {
        InputStream in = JdbcPool.class.getClassLoader().getResourceAsStream("db.properties");
        Properties prop = new Properties();
        try {
            prop.load(in);
            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");
            String userName = prop.getProperty("userName");
            String userPwd = prop.getProperty("userPwd");

            int jdbcPoolInitSize = Integer.parseInt(prop.getProperty("jdbcPoolInitSize"));

            Class.forName(driver);

            for (int i = 0; i < jdbcPoolInitSize; i++) {
                Connection connection = DriverManager.getConnection(url, userName, userPwd);
                System.out.println("获取到连接" + connection);

                listConnections.add(connection);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (listConnections.size() > 0) {
            final Connection connection = listConnections.removeFirst();
            System.out.println("listConnections数据库连接池大小是：" + listConnections.size());

            //动态代理，返回Connection 对象的代理对象 ???
            return (Connection) Proxy.newProxyInstance(
                    this.getClass().getClassLoader(),
                    connection.getClass().getInterfaces(),
                    (Object proxy, Method method, Object[] args) -> {
                        if (!method.getName().equals("close")) {
                            return method.invoke(connection, args);
                        } else {
                            listConnections.add(connection);
                            System.out.println(connection + "被还给listConnections数据库连接池");
                            System.out.println("listConnections数据库连接池大小为：" + listConnections.size());
                            return null;
                        }
                    });
        } else {
            throw new RuntimeException("数据库忙！");
        }
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
